import { defineStore } from 'pinia'
import { ref } from 'vue'
import { markMessageRead, markAllMessagesRead, deleteMessage as deleteMessageApi, clearAllMessages as clearAllMessagesApi } from '@/api/system/message'

export interface Message {
  id: string | number
  title: string
  content: string
  time: string
  type?: string
  typeText?: string
  read: boolean
}

export const useMessageStore = defineStore('message', () => {
  const unreadCount = ref(0)
  const messages = ref<Message[]>([])
  
  // 更新未读消息数量
  const updateUnreadCount = (count: number) => {
    unreadCount.value = count
  }

  // 更新消息列表
  const updateMessages = (newMessages: Message[]) => {
    messages.value = newMessages
  }

  // 标记消息为已读
  const markAsRead = async (messageId: string | number) => {
    try {
      await markMessageRead(messageId)
      const message = messages.value.find(msg => msg.id === messageId)
      if (message) {
        message.read = true
        unreadCount.value--
      }
    } catch (error) {
      console.error('标记消息已读失败:', error)
      throw error
    }
  }

  // 标记所有消息为已读
  const markAllAsRead = async () => {
    try {
      await markAllMessagesRead()
      messages.value.forEach(msg => {
        if (!msg.read) {
          msg.read = true
        }
      })
      unreadCount.value = 0
    } catch (error) {
      console.error('标记所有消息已读失败:', error)
      throw error
    }
  }

  // 删除消息
  const deleteMessage = async (messageId: string | number) => {
    try {
      await deleteMessage(messageId)
      const index = messages.value.findIndex(msg => msg.id === messageId)
      if (index > -1) {
        const message = messages.value[index]
        messages.value.splice(index, 1)
        if (!message.read) {
          unreadCount.value--
        }
      }
    } catch (error) {
      console.error('删除消息失败:', error)
      throw error
    }
  }

  // 清空所有消息
  const clearAllMessages = async () => {
    try {
      await clearAllMessages()
      messages.value = []
      unreadCount.value = 0
    } catch (error) {
      console.error('清空所有消息失败:', error)
      throw error
    }
  }

  return {
    unreadCount,
    messages,
    updateUnreadCount,
    updateMessages,
    markAsRead,
    markAllAsRead,
    deleteMessage,
    clearAllMessages
  }
})